package com.framework.utils.jiufu;

import com.framework.exception.RRException;
import net.sf.json.JSONObject;

import java.util.*;
import java.util.Map.Entry;


public class ShopUtil {

	/**
	 * 验签秘钥
	 */
	public static final String WALLET= "4qjtgM8Eo3Zd89Vn7z9X6A==";
	
	public static final String CHANNEL_ID = "IB9H1CHM";
	
	public static final String BANK_URL = "http://wkmanager.9fbank.com/offchannel/wkChannelBinding/getshopUrl";
	
	public static final String SHOP_NAME = "BAIYI";
	

  
	public static String sign(String salt,String ... kv){
		LinkedHashMap<String,String> paramMap = getParamLinkedMap(kv);
		if(paramMap!=null){
			return sign(paramMap, salt);
		}
		return null;
	}
	/**
	 * 验签功能
	 * @param salt 加签验签秘钥
	 * @param sign url 传递过来的 加密后的字符串
	 * @param kv 以键值对组成的参数
	 *      <p>如：userId=xxx,mobile=156</p>
	 *      <p>输入时为 verifySign(sign,"userId","xxx","mobile","156")</p>
	 * @return 
	 *     <p>kv不为双数,返回false</p>
	 *     <p>计算出的sign和传递过来的sign一致， 返回true</p>
	 *     <p>计算出的sign和传递过来的sign不一致，返回false</p>
	 */
	public static boolean verifySign(String salt,String sign,String ... kv){
		LinkedHashMap<String,String> paramMap = ShopUtil.getParamLinkedMap(kv);
		if(paramMap!=null){
			String signVal = ShopUtil.sign(paramMap, salt);
			if(signVal!=null&&signVal.equals(sign)){
				return Boolean.TRUE;
			}
		}
		return Boolean.FALSE;
	}
	/**
	 * 加签
	 * @param paraMap 按约定顺序传入的参数和值
	 * @param secretKey 秘钥 
	 * @return
	 */
	public static String sign(LinkedHashMap<String, String> paraMap, String secretKey){
		if(paraMap==null||paraMap.size()<=0){
			return null;
		}
		StringBuffer strBuf=new StringBuffer();
		for(Entry<String,String> ent:paraMap.entrySet()){
			strBuf.append(ent.getKey()).append(":");
			if(ent.getValue() == null){
            }else{
				strBuf.append(ent.getValue());
			}
		}
		String str = EncryptUtil.getInstance().MD5(strBuf.toString().replaceAll("!", ""), secretKey);
		return StringUtils.getReplaceStr(str);
	}
	/**
	 * 验签 
	 * @param paraMap 参数Map
	 * @param secretKey 秘钥
	 * @param sign  传递过来的加签值
	 * @return
	 */
	public static boolean verifySign(LinkedHashMap<String, String> paraMap, String secretKey,String sign){
		String signVal = sign(paraMap, secretKey);
		if(signVal!=null&&signVal.equals(sign)){
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}
	/**
	 * 将参数封装到 LinkedHashMap中
	 * @param str key value,key value 的数组
	 * @return
	 */
	public static LinkedHashMap<String, String> getParamLinkedMap(String ...str){
		if(str!=null&&(str.length%2==0)){
			LinkedHashMap<String, String> linkedMap=new LinkedHashMap<String, String>();
			for(int i=0;i<str.length/2;i++){
				linkedMap.put(str[i*2], str[i*2+1]);
			}
			return linkedMap;
		}
		return null;
	} 
	
	/**
	* @desc: 去掉空值与签名参数sign后的新签名参数
	* @authorhbt
	* @param sArray 签名参数组
	* @return
	 */
	private static Map<String, String> paraFilter(Map<String, String> sArray) {

        Map<String, String> result = new HashMap<String, String>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || "".equals(value) || "sign".equalsIgnoreCase(key)) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }

    /**
     * 把所有参数按key排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @authorhbt
     * @param params 参数
     * @return 拼接后字符串
     */
    private static String createLinkString(Map<String, String> params) {
    	Map<String, String> newParms = paraFilter(params);
        List<String> keys = new ArrayList<String>(newParms.keySet());
        Collections.sort(keys);
        StringBuilder prestr = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = newParms.get(key);
			//拼接时，不包括最后一个&字符
            if (i == keys.size() - 1) {
				prestr = prestr.append(key).append("=").append(value);
            } else {
                prestr = prestr.append(key).append("=").append(value).append("&");
            }
        }
        return prestr.toString();
    }
	/**
	* @desc: 获取排序后的签名字符串
	* @authorhbt
	* @param paraMap 要签名的参数
	* @param secretKey 密钥
	* @return
	 */
    public static String getSign(Map<String, String> paraMap, String secretKey){
    	String prestr = createLinkString(paraMap);
    	String str = EncryptUtil.getInstance().MD5(prestr.replaceAll("!", ""), secretKey);
    	str = (str == null ? "" : str);
		return StringUtils.getReplaceStr(str);
    }
    /**
    * @desc: 将参数自动排序后验证签名 
    * @authorhbt
    * @param params  URL参数
    * @param secretKey 密钥
    * @return
     */
    public static boolean veryfy(Map<String, String> params, String secretKey) {
    	//获取签名结果
		String sign = "";
		if (params != null && params.get("sign") != null) {
			sign = params.get("sign");
		}
    	String newSign = getSign(params, secretKey);
        //获得签名验证结果
    	return sign.equals(newSign);
    }
    
    /**
	 * 验签功能，匹配所有
	 * @param sign url 传递过来的 加密后的字符串
	 * @param kv 以键值对组成的参数
	 *      <p>如：userId=xxx,mobile=156</p>
	 *      <p>输入时为 verifySign(sign,"userId","xxx","mobile","156")</p>
	 * @return 
	 *     <p>kv不为双数,返回false</p>
	 *     <p>计算出的sign和传递过来的sign一致， 返回true</p>
	 *     <p>计算出的sign和传递过来的sign不一致，返回false</p>
	 */
/*	protected boolean verifySign(String sign,String ... kv){
		LinkedHashMap<String,String> paramMap = SignUtil.getParamLinkedMap(kv);
		if(paramMap!=null){			
				String signVal = SignUtil.sign(paramMap, SignUtil.WK_MANAGER);
				if(signVal!=null&&signVal.equals(sign)){
					return Boolean.TRUE;
				
			}
		}
		return Boolean.FALSE;
	}*/
    
    /**
     * 获取信用卡个人所属的id
     * @param mobile
     * @param
     * @return
     */
    public static String getShopId(String mobile){
		String channelId = CHANNEL_ID;
		String t = String.valueOf(System.currentTimeMillis());
		System.out.print(t);
		String sign = sign(ShopUtil.WALLET, "mobile",mobile,"shopName",SHOP_NAME,"channelId",channelId,"_t",t);
		System.out.println(sign);
		Map<String, Object> map = new HashMap<>();
		map.put("mobile", mobile);
		map.put("shopName", SHOP_NAME);
		map.put("channelId", channelId);
		map.put("sign", sign);
		map.put("_t", t);
		String res = HttpClientHelper.httpClientPost(BANK_URL,map, "UTF-8",null);
		System.out.println(res);
		JSONObject jsonObj = JSONObject.fromObject(res);
		String status = (String)jsonObj.get("status");
		if(res == null || !StringUtils.equals(status, "1")){
			throw new RRException("9000","获取shopId错误");
		}else{
			Object data = jsonObj.get("data");
			JSONObject dataObj = JSONObject.fromObject(data);
			String shopId = (String)dataObj.get("shopId");
			return shopId;
		}
    }

	public static void main(String[] args) {
		System.out.println(getShopId("17707432612"));
	}
}
